<?php
	App::import('Vendor','Cms.SiteTree/TreeIndexer');
	App::import('Vendor','Cms.SiteTree/BreadCrumb');
	class BreadCrumbHelper extends AppHelper
	{
		var $SiteTreeCallbacksObject;
		function show($urlInfo,$file=null)
		{
			if($file == null)
			{
				$file = CONFIGS.'url'.DS.'site.xml';		
			}
			$breadCrumbInfo = $this->getBreadCrumb($urlInfo,$file);
			$breadCrumbElement = 'bread_crumb';
			if(isset($this->breadCrumbElement) && strlen($this->breadCrumbElement) > 1)
			{
				$breadCrumbElement =$this->breadCrumbElement;
			}
			return $this->getView()->element($breadCrumbElement,array('breadCrumbElements'=>$breadCrumbInfo,'plugin'=>false));
		}
		
		function showFromPresentUrl($file = null)
		{
			$urlKeys = array('named','pass','action','plugin','controller');
			$url = array_intersect_key($this->params,array_combine($urlKeys,$urlKeys));
			$urlInfo = array('url'=>$url,'title'=>$this->getView()->pageTitle);
			return $this->show($urlInfo,$file);
		}
		
		function getBreadCrumb($urlInfo,$file=null)
		{
			if(!is_object($this->SiteTreeCallbacksObject))
			{
				$this->SiteTreeCallbacksObject = new SiteTreeCallbacks;
			}
			$IndexTree = $this->getIndexTree($file);
			$BreadCrumb = new BreadCrumb($this->SiteTreeCallbacksObject);
			$breadCrumbInfo = $BreadCrumb->getBreadCrumb($IndexTree,$urlInfo);
			return $breadCrumbInfo;
		}
		private function getIndexTree($file)
		{
			$cacheKey = 'site_tree_'.md5($file);
			GigaCache::set(array('duration'=>"+2 hour",'path'=>CACHE));
			$IndexTree = GigaCache::read($cacheKey);
			if(!is_object($IndexTree))
			{
				$IndexTree = new SiteTreeIndexer();
				$IndexTree->loadAndParse($file);
				GigaCache::write($cacheKey,$IndexTree);
			}
			return $IndexTree;		
		}
		
		function getUrlFromUrlIfo($urlInfo = array())
		{
			$urlKeys = array('action','plugin','controller');
			$url = array_intersect_key($urlInfo['url'],array_combine($urlKeys,$urlKeys));
			$url = am($urlInfo['url']['named'],$url);
			$url = am($urlInfo['url']['pass'],$url);
			return $url;
		}
	}
?>